package com.seven.controller;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.time.LocalDateTime;
import java.util.concurrent.Executors;

/**
 * @author WenJieYin
 **/
@RestController
@RequestMapping("test")
public class HttpTestController {

    @GetMapping("next")
    public String hello(String name) {
        return name;
    }

    @PostMapping("up")
    public void up(@RequestParam("file") MultipartFile file) {
        System.out.println(file.getOriginalFilename() + ": " + file.getSize());
    }

    @GetMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter stream() {
        SseEmitter emitter = new SseEmitter();

        // 异步发送消息
        Executors.newSingleThreadExecutor().submit(() -> {
            try {
                for (int i = 1; i <= 5; i++) {
                    emitter.send("消息 " + i + " @ " + LocalDateTime.now());
                    Thread.sleep(1000);
                }
                emitter.complete(); // 通知客户端关闭连接
            } catch (Exception e) {
                emitter.completeWithError(e);
            }
        });

        return emitter;
    }
}
